package com.crowd.util;


import com.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Stone
 * @date 2020/4/29 20:51
 * 判断是否是ajax请求，是返回true，否返回false
 */
public class CrowdUtil {

    /**
     * @Author:Stone
       * @Param request:
       * @return: boolean
     * @Date: 2020/5/8
     * @Description:用于判断是否为ajax请求
    */
    public static boolean judgeRequestType(HttpServletRequest request){
        String accpet = request.getHeader("Accept");
        String xRequest = request.getHeader("X-Requested-With");

        // 2.检查并返回
        return (accpet != null && accpet.contains("application/json"))
                || (xRequest != null  && xRequest.equals("XMLHttpRequest"));
    }

    /**
     * @Author:Stone
       * @Param source: 
       * @return: java.lang.String
     * @Date: 2020/5/8 15:36
     * @Description:
    */
    public static String md5(String source){
        // 1.判断source是否是空指针或者长度为0
        if(source==null || source.length()==0){
            // 2.如果是空指针，抛异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        try {
            // 3.获取MessageDigest 对象
            String algorithm = "md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            // 4.获取明文字符串对应的字节数组
            byte[] input = source.getBytes();
            // 5.执行加密
            byte[] output = messageDigest.digest(input);
            // 6.创建BigInteger 对象
            // BigInteger(int signum, byte[] magnitude)
            // 此构造函数用于将BigInteger的符号大小表示法转换成一个BigInteger值。符号位，负数是为-1，零时为0，正数是为1
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, output);
            // 7.按照16 进制将bigInteger 的值转换为字符串
            int radix = 16;
            String encoded = bigInteger.toString(radix).toUpperCase();

            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;

    }

}
